import time
from datetime import datetime
from typing import Any

from sqlmodel import Session, select, func

from app.exception.base import AppException, HttpResp
from app.models.base import PageListOut
from app.models.system_role import SystemRole, SystemRoleEditIn, SystemRoleAddIn, SystemRoleListIn, SystemRoleOut


class SystemRoleService:
    def __init__(self, session: Session):
        self.session = session

    async def page_list(self, list_in: SystemRoleListIn) -> Any:
        name = list_in.name
        is_stop = list_in.isStop
        page_no = list_in.page_no
        page_size = list_in.page_size
        # SystemRole.delete_time.is_(None)
        where = []
        if name:
            where.append(SystemRole.name.like('%{0}%'.format(name)))
        if is_stop is not None:
            where.append(SystemRole.is_stop == is_stop)

        count_statement = (
            select(func.count())
            .select_from(SystemRole)
            .where(*where)
        )
        count = self.session.exec(count_statement).one()
        offset = (page_no - 1) * page_size
        statement = (
            select(SystemRole).where(*where).offset(offset).limit(page_size)
        )
        lists = self.session.exec(statement).all()
        return lists, count

    async def detail(self, id_: int):
        menu = self.session.get(SystemRole, id_)
        return menu

    async def add(self, create_in: SystemRoleAddIn):
        """新增菜单"""
        create_dict = create_in.dict()
        create_dict['create_time'] = int(time.time())
        create_dict['update_time'] = int(time.time())
        menu_item = SystemRole(**create_dict)
        self.session.add(menu_item)
        self.session.commit()
        self.session.refresh(menu_item)
        return menu_item

    async def edit(self, edit_in: SystemRoleEditIn,):
        role_item = self.session.get(SystemRole, edit_in.id)
        if not role_item:
            raise AppException(HttpResp.FAILED, msg='数据不存在!')
        # 更新菜单项的字段
        for key, value in edit_in.dict().items():
            if hasattr(role_item, key):
                setattr(role_item, key, value)

        # 更新 update_time 字段
        role_item.update_time = datetime.now()
        # 提交更改到数据库
        self.session.commit()
        self.session.refresh(role_item)
        return role_item

    async def delete(self, id_: int):
        menu = self.session.get(SystemRole, id_)
        return menu

    async def get_by_id(self, id_: int):
        menu = self.session.get(SystemRole, id_)
        return menu

    async def get_member_count(self, role_id: int):
        """根据角色ID获取成员数量"""
        where = [SystemRole.delete_time.is_(None)]
        count_statement = (
            select(func.count())
            .select_from(SystemRole)
            .where(*where)
        )
        # await db.fetch_val(
        #     select(func.count(SystemRole.id))
        #     .where(func.find_in_set(role_id, SystemRole.role_ids), SystemRole.is_delete == 0))
        count = self.session.exec(count_statement).one()
        return count
